package com.sxj.web.jsp;

import com.sxj.web.util.CookieUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 石小俊
 * @date 2024年03月08日 20:49
 * 用户登录功能
 * 当登录页面提交的时候访问该Servlet
 * 判断用户所输入的用户名与密码是否正确
 * 如果正确
 * 则将正确的用户名与密码保存到Cookie中
 * 且页面跳转到主页main.jsp
 * 如果不正确
 * 则页面跳转到登录页面login.jsp
 * 且在登录页面中显示错误消息:用户名或密码错误
 * 使用假数据,假设数据库中存在一个账号,用户名admin，密码123456
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单中输入的用户名与密码
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String time = request.getParameter("time");
        // 判断用户名与密码是否正确
        // 判断用户在页面中输入的是否正确
        if ("admin".equals(username) && "123456".equals(password)) {
            if ("week".equals(time)) {
                CookieUtil.addCookie("username", username, 7 * 24 * 60 * 60, response);
                CookieUtil.addCookie("password", password, 7 * 24 * 60 * 60, response);
            } else if ("month".equals(time)) {
                CookieUtil.addCookie("username", username, 30 * 24 * 60 * 60, response);
                CookieUtil.addCookie("password", password, 30 * 24 * 60 * 60, response);
            } else if ("year".equals(time)) {
                CookieUtil.addCookie("username", username, 365 * 24 * 60 * 60, response);
                CookieUtil.addCookie("password", password, 365 * 24 * 60 * 60, response);
            }
//            request.getRequestDispatcher("/jsp/main.jsp").forward(request, response);
            response.sendRedirect(request.getContextPath()+"/showMain");
        } else {
            request.setAttribute("loginMsg", "用户名或密码错误");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
        }
    }
}
